package com.guet.upsum.service.impl;

import com.guet.issue.service.IIssueService;
import com.guet.upsum.beans.entity.Upsum;
import com.guet.upsum.beans.vo.UpsumVO;
import com.guet.upsum.mapper.UpsumMapper;
import com.guet.upsum.service.IUpsumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Li
 * @create 2022-12-20-12:29
 */
@Service
public class UpsumServiceImpl implements IUpsumService {
    @Autowired
    UpsumMapper upsumMapper;

    @Autowired
    IIssueService issueService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UpsumVO up(Integer userId, Integer issueId) {

        UpsumVO upsumVO = new UpsumVO();

        Upsum upsum = upsumMapper.select(userId, issueId);

        if (upsum == null){
            upsumMapper.add(userId, issueId);
            issueService.updateSum(1, issueId);

            Integer sum = issueService.selectSum(issueId);
            upsumVO.setUpsum(sum);
            upsumVO.setStatus(true);
            return upsumVO;
        } else {
            upsumMapper.delete(upsum.getId());
            issueService.updateSum(-1, issueId);
            Integer sum = issueService.selectSum(issueId);
            upsumVO.setUpsum(sum);
            upsumVO.setStatus(false);
            return upsumVO;
        }

    }

    @Override
    public UpsumVO select(Integer userId, Integer issueId) {

        UpsumVO upsumVO = new UpsumVO();

        Integer sum = issueService.selectSum(issueId);

        Upsum upsum = upsumMapper.select(userId, issueId);

        if (upsum == null){
            upsumVO.setStatus(false);
        } else {
            upsumVO.setStatus(true);
        }

        upsumVO.setUpsum(sum);

        return upsumVO;

    }
}
